<template>
    <div class="app-container">
        <!-- 操作面板 -->
        <el-card class="operation-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <span class="card-title">教室管理操作</span>
                </div>
            </template>
            
            <!-- 文件操作区域 -->
            <div class="operation-section">
                <div class="section-title">文件操作</div>
                <div class="button-group">
                    <el-upload 
                        ref="uploadRef" 
                        accept=".xls,.xlsx" 
                        action="/api/uploadRoom"
                        :on-remove="handleRemove" 
                        :on-error="handleError" 
                        :on-success="uploadSuccess" 
                        :disabled="importBtnDisabled"
                        :file-list="fileList" 
                        :auto-upload="false" 
                        :limit="1"
                        class="upload-component"
                    >
                        <template #trigger>
                            <el-button type="primary" :icon="UploadFilled">
                                从Excel导入
                            </el-button>
                        </template>
                        <el-button type="success" :loading="loading" @click="submitUpload" :icon="Upload">
                            上传到服务器
                        </el-button>
                        
                    </el-upload>

                    <el-button type="info" @click="downloadTemplate()" :icon="Download">
                        下载模板
                    </el-button>
                    <div class="upload-tip">
                                只能上传xls/xlsx文件，导入新班级后将清空原来的班级，请一次性将本学期班级导入完毕
                    </div>
                </div>
            </div>
            
            <!-- 数据操作区域 -->
            <div class="operation-section">
                <div class="section-title">数据操作</div>
                <div class="button-group">
                    <el-button type="primary" @click="handleAdd" :icon="Plus">
                        新增教室
                    </el-button>
                    <el-button 
                        type="danger" 
                        @click="handleBatchDelete" 
                        :disabled="multipleSelection.length === 0"
                        :icon="Delete"
                    >
                        批量删除 ({{ multipleSelection.length }})
                    </el-button>
                </div>
            </div>
        </el-card>

        <!-- 展示上传后的结果 -->
        <el-table v-loading="listLoading" :data="paginatedData" element-loading-text="Loading" border fit
            highlight-current-row @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            
            <el-table-column align="center" label="序号" width="60px">
                <template #default="scope">
                    {{ scope.$index + 1 + (currentPage - 1) * pagesize }}
                </template>
            </el-table-column>

            <el-table-column label="教室编号" prop="roomNo" align="center">
                <template #default="scope">
                    {{ scope.row.roomNo }}
                </template>
            </el-table-column>
            <el-table-column label="教室名" prop="roomName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.roomName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="教学区域编号" prop="areaNo" align="center">
                <template #default="scope">
                    {{ scope.row.areaNo }}
                </template>
            </el-table-column>
            <el-table-column label="教室容量" prop="capacity" align="center">
                <template #default="scope">
                    <span>{{ scope.row.capacity }}</span>
                </template>
            </el-table-column>
            <el-table-column label="教室属性" prop="attr" align="center">
                <template #default="scope">
                    {{ scope.row.attr }}
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" align="center">
                <template #default="scope">
                    <span>{{ scope.row.remark }}</span>
                </template>
            </el-table-column>
            
            <el-table-column label="操作" align="center" width="200px">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
            style="margin-top: 1rem; margin-left: 0.4rem"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="list.length"
        >
        </el-pagination>
        
        <!-- 新增/编辑对话框 -->
        <el-dialog
            :title="dialogTitle"
            v-model="dialogVisible"
            width="600px"
            :before-close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="120px"
            >
                <el-form-item label="教室编号" prop="roomNo">
                    <el-input v-model="form.roomNo" placeholder="请输入教室编号"></el-input>
                </el-form-item>
                <el-form-item label="教室名称" prop="roomName">
                    <el-input v-model="form.roomName" placeholder="请输入教室名称"></el-input>
                </el-form-item>
                <el-form-item label="教学区域编号" prop="areaNo">
                    <el-input v-model="form.areaNo" placeholder="请输入教学区域编号"></el-input>
                </el-form-item>
                <el-form-item label="教室容量" prop="capacity">
                    <el-input-number v-model="form.capacity" :min="1" :max="500" placeholder="请输入教室容量"></el-input-number>
                </el-form-item>
                <el-form-item label="教室属性" prop="attr">
                    <el-input v-model="form.attr" placeholder="请输入教室属性"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Upload, UploadFilled, Download, Plus, Delete } from '@element-plus/icons-vue';
import axios from 'axios';

const list = ref([]);
const listLoading = ref(true);
const fileList = ref([]);
const loading = ref(false);
const importBtnDisabled = ref(false);
const uploadRef = ref(null);

// 分页相关
const currentPage = ref(1);
const pagesize = ref(10);

// 多选相关
const multipleSelection = ref([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);
const form = ref({
    id: null,
    roomNo: '',
    roomName: '',
    areaNo: '',
    capacity: null,
    attr: '',
    remark: ''
});

// 表单验证规则
const rules = {
    roomNo: [{ required: true, message: '请输入教室编号', trigger: 'blur' }],
    roomName: [{ required: true, message: '请输入教室名称', trigger: 'blur' }],
    areaNo: [{ required: true, message: '请输入教学区域编号', trigger: 'blur' }],
    capacity: [{ required: true, message: '请输入教室容量', trigger: 'blur' }]
};

// 分页数据
const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pagesize.value;
    const end = start + pagesize.value;
    return list.value.slice(start, end);
});

// 移除了 paginatedList 计算属性

const getList = async () => {
    listLoading.value = true;
    try {

 
        const response = await axios.get('/api/room/getList',{
          headers: {
            "token": localStorage.getItem("token"),
          },
        })
        
        list.value = response.data.data || [];
        if (list.value.length === 0) {
            ElMessage({ message: '暂无教室', type: 'success' });
        }
    } catch (error) {
        console.error('Error fetching list:', error);
        ElMessage({ message: '获取列表失败', type: 'error' });
    } finally {
        listLoading.value = false;
    }
};

const downloadTemplate = () => {
    window.location.href = '/api/downloadRoom';
};

const uploadSuccess = (response, file, uploadedFileList) => {
    loading.value = false;
    getList();
    ElMessage({ message: '上传成功', type: 'success' });
    fileList.value = [];
    if (uploadRef.value) {
        uploadRef.value.clearFiles();
    }
};

const handleRemove = (file, uploadedFileList) => {
    // console.log('Removed file:', file, uploadedFileList);
};

const handleError = (error, file, uploadedFileList) => {
    loading.value = false;
    console.error('Upload error:', error);
    const errorMessage = error instanceof Error ? error.message : '文件上传失败';
    ElMessage({ message: errorMessage, type: 'error' });
    if (uploadRef.value) {
        uploadRef.value.clearFiles();
    }
};

const submitUpload = () => {
    if (uploadRef.value) {
        loading.value = true;
        uploadRef.value.submit();
    } else {
        ElMessage({ message: '上传组件未准备好', type: 'warning' });
    }
};

// 分页方法
const handleSizeChange = (val) => {
    pagesize.value = val;
    currentPage.value = 1;
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
};

// 多选处理
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 新增教室
const handleAdd = () => {
    dialogTitle.value = '新增教室';
    resetForm();
    dialogVisible.value = true;
};

// 编辑教室
const handleEdit = (row) => {
    dialogTitle.value = '编辑教室';
    form.value = { ...row };
    dialogVisible.value = true;
};

// 删除单个教室
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm('此操作将永久删除该教室, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        
        const response = await axios.delete(`/api/room/delete/${row.id}`, {
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        
        if (response.data.code === 200) {
            ElMessage({ message: '删除成功', type: 'success' });
            getList();
        } else {
            ElMessage({ message: response.data.message || '删除失败', type: 'error' });
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error);
            ElMessage({ message: '删除失败', type: 'error' });
        }
    }
};

// 批量删除
const handleBatchDelete = async () => {
    if (multipleSelection.value.length === 0) {
        ElMessage({ message: '请选择要删除的教室', type: 'warning' });
        return;
    }
    
    try {
        await ElMessageBox.confirm(`此操作将永久删除选中的${multipleSelection.value.length}个教室, 是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        
        const ids = multipleSelection.value.map(item => item.id);
        const response = await axios.delete('/api/room/deleteBatch', {
            data: ids,
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        
        if (response.data.code === 200) {
            ElMessage({ message: '批量删除成功', type: 'success' });
            getList();
            multipleSelection.value = [];
        } else {
            ElMessage({ message: response.data.message || '批量删除失败', type: 'error' });
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error);
            ElMessage({ message: '批量删除失败', type: 'error' });
        }
    }
};

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;
    
    try {
        await formRef.value.validate();
        
        const url = form.value.id ? '/api/room/update' : '/api/room/add';
        const method = form.value.id ? 'put' : 'post';
        
        const response = await axios[method](url, form.value, {
            headers: {
                "token": localStorage.getItem("token")
            }
        });
        
        if (response.data.code === 200) {
            ElMessage({ message: form.value.id ? '更新成功' : '新增成功', type: 'success' });
            dialogVisible.value = false;
            getList();
        } else {
            ElMessage({ message: response.data.message || '操作失败', type: 'error' });
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage({ message: '操作失败', type: 'error' });
    }
};

// 重置表单
const resetForm = () => {
    form.value = {
        id: null,
        roomNo: '',
        roomName: '',
        areaNo: '',
        capacity: null,
        attr: '',
        remark: ''
    };
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false;
    resetForm();
};

onMounted(() => {
    getList();
});

</script>

<style scoped>
.app-container {
    padding: 20px;
}

.operation-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.operation-section {
    margin-bottom: 20px;
}

.operation-section:last-child {
    margin-bottom: 0;
}

.section-title {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
}

.button-group {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: center;
}

.upload-component {
    display: flex;
    align-items: center;
    gap: 8px;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
    margin-top: 8px;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border-left: 3px solid #409eff;
}

.el-button {
    border-radius: 6px;
}

.el-card {
    border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .button-group {
        flex-direction: column;
        align-items: stretch;
    }
    
    .upload-component {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>